﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace EncoderTester
{
    class NumericTextBox : TextBox
    {
        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register("Minimum", typeof(double), typeof(NumericTextBox), new PropertyMetadata(Double.MinValue));

        public static readonly DependencyProperty MaximumProperty =
            DependencyProperty.Register("Maximum", typeof(double), typeof(NumericTextBox), new PropertyMetadata(Double.MaxValue));

        public double Minimum
        {
            get { return (double)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty, value); }
        }

        public double Maximum
        {
            get { return (double)GetValue(MaximumProperty); }
            set { SetValue(MaximumProperty, value); }
        }

        protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
        {
            string txt = (this.Text == null) ? String.Empty : this.Text;
            txt = txt.Insert(this.CaretIndex, e.Text);
            if (txt.Equals("-") && Minimum < 0) base.OnPreviewTextInput(e);
            else
            {
                double result;
                if (Double.TryParse(txt, out result) && result <= Maximum)
                {
                    base.OnPreviewTextInput(e);
                }
                else e.Handled = true;
            }
        }
    }
}
